<?php
class LeksemObjModel extends Model {
	
	/**
	 * Get leksem by id
	 *
	 * @param integer $id
	 * @return array
	 */
	public function getLeksById($id) {
		$queryString = sprintf("
			SELECT 
				`leks`.`id`, `leks`.`name`, `leks`.`context`, `leks`.`id_user`, `leks`.`translated`,`leks`.`id_website`, `base`.`value`
			FROM
				`leks`, `base`
			WHERE
				`leks`.`id`=`base`.`id_leks` AND `leks`.`id` = %d;
		", $id 
		);
		$result = $this->_sqlInstance->query($queryString);
		return $result;
	}
	
	/**
	 * Save leksem
	 *
	 * @param Leksem $item
	 * @return mysqli_result
	 */
	public function save(Leksem $leksem) {
		$queryString = sprintf("
			INSERT INTO
				`leks`(`id_user`, `name`, `context`, `translated`, `id_website`)
			VALUES
				(%d, '%s', '%s', %d, %d);
		",$leksem->userId, $leksem->name, $leksem->context, $leksem->translated, $leksem->websiteId);
		
		$this->_sqlInstance->query($queryString);
		
		$insertedId = $this->_sqlInstance->getLastInsertId();
		
		$queryInsertBase = sprintf("
			INSERT INTO
				`base`(`id_leks`, `value`)
			VALUES
				(%d, '%s');
		", $insertedId, $leksem->value);
		$this->_sqlInstance->query($queryInsertBase);

		//return $result;
	}
	
	public function markTranslated($id) {
		$queryString = sprintf("
			UPDATE
				`leks`
			SET
				`leks`.`translated` = 1
			WHERE
				`leks`.`id` = %d;
		", $id);
		
		$this->_sqlInstance->query($queryString);
	}
	
	public function delete($id) {
		$queryString = sprintf("
			DELETE FROM
				`leks`
			WHERE
				`leks`.`id` = %d
		", $id);
		$this->_sqlInstance->query($queryString);
	}
	
	public function update(Leksem $leks) {
		$queryStringLeks = sprintf("
			UPDATE
				`leks`
			SET 
				`leks`.`name` = '%s',
                `leks`.`context` = '%s',
				`leks`.`translated` = 0
			WHERE 
				`leks`.`id` = %d
		", $leks->name, $leks->context, $leks->id);
        $queryStringBase = sprintf("
			UPDATE 
				`base`
			SET
				`base`.`value` = '%s'
			WHERE
				`base`.`id_leks` = %d;
		", $leks->value, $leks->id);
		$this->_sqlInstance->query($queryStringLeks);
		$this->_sqlInstance->query($queryStringBase);
	}

    public function getTranslatedInto($id, $dictId) {
        $queryString = sprintf("
            SELECT
                `t`.`value`
            FROM
                `translation` AS `t`
            WHERE
                `t`.`id_leks` = %d
            AND
                `t`.`id_dict` = %d;
        ", $id, $dictId);
        $result = $this->_sqlInstance->query($queryString);
        return $result;
    }
}